package com.mao.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mao.common.CustomException;

import com.mao.entity.Category;
import com.mao.entity.Dish;
import com.mao.entity.Setmeal;
import com.mao.mapper.CategoryMapper;
import com.mao.service.CategoryService;
import com.mao.service.DishService;
import com.mao.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService ds;

    @Autowired
    private SetmealService ss;

    @Override
    public void remove(Long ids) {
        //判断菜品有什么关联其他菜
        //1.创建条件构造器
        LambdaQueryWrapper<Dish> lq =new LambdaQueryWrapper<>();
        lq.eq(Dish::getCategoryId,ids);
        int count = ds.count(lq);
        //如果大于0则有关联其他菜品，所以抛出异常
        if (count>0){
            //3.与菜品关联了，抛出异常
                throw new CustomException("与菜品关联了,不能删除");
        }

        //判断套餐有什么关联其他菜
        //1.创建条件构造器
        LambdaQueryWrapper<Setmeal> lq2 =new LambdaQueryWrapper<>();
        //2.添加条件
        lq2.eq(Setmeal::getCategoryId,ids);
        int count1 = ss.count(lq2);
        //3.与套餐关联了，抛出异常
        if (count1>0){
            throw new CustomException("与套餐关联了,不能删除");
        }

        //无关联，正常删除
        super.removeById(ids);
    }

    @Override
    public Page get_page(int page, int pageSize) {
        //创建分页构造器
        Page<Category> pageInfo=new Page<>(page,pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Category> lq =new LambdaQueryWrapper<>();
        //添加排序条件
        lq.orderByAsc(Category::getSort);
        this.page(pageInfo,lq);
        return pageInfo;
    }

    @Override
    public List<Category> get_list(Category category) {
        //获取所有分类数据
        //1.条件构造器
        LambdaQueryWrapper<Category> clw=new LambdaQueryWrapper<>();
        //2.添加条件
        clw.eq(category.getType()!=null,Category::getType,category.getType());
        //3.添加排序
        clw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //4.查询并返回list集合数据
        List<Category> categoryList = this.list(clw);
        return categoryList;
    }
}
